#include "Buzzer.h"

BUzzerControl_t buzzer_control = {0};
uint8_t buzzer_state = 0; // 0: off, 1: on
uint16_t buzzer_on_time = 0; // 蜂鸣器开启时间

void buzzer_on(void)
{
    buzzer_on_time = uwTick;
    HAL_GPIO_WritePin(GPIOC, GPIO_PIN_9, GPIO_PIN_SET); // 设置PC9引脚为高电平
    buzzer_state = 1; // 设置蜂鸣器状态为开启
}

void buzzer_off(void)
{
    HAL_GPIO_WritePin(GPIOC, GPIO_PIN_9, GPIO_PIN_RESET); // 设置PC9引脚为低电平
    buzzer_on_time = 0; // 重置蜂鸣器开启时间
    buzzer_state = 0; // 设置蜂鸣器状态为关闭
}

void buzzer_beep(uint8_t times, uint32_t on_ms, uint32_t off_ms)
{
    buzzer_control.is_running = 1;
    buzzer_control.state = 0; // 关闭
    buzzer_control.count = 0; // 重置计数
    buzzer_control.target_count = times;
    buzzer_control.on_time = on_ms;
    buzzer_control.off_time = off_ms;
    buzzer_control.last_tick = uwTick;
    buzzer_off(); // 确保蜂鸣器先关闭
}

void buzzer_run(void)
{
    if(!buzzer_control.is_running) return; // 如果蜂鸣器不在运行状态，直接返回

    if(buzzer_control.state == 0) // 关闭状态
    {
        if(uwTick - buzzer_control.last_tick >= buzzer_control.off_time)
        {
            if(buzzer_control.count < buzzer_control.target_count)
            {
                buzzer_on(); // 开启蜂鸣器
                buzzer_control.state = 1; // 切换到开启状态
                buzzer_control.last_tick = uwTick; // 更新最后操作时间
            }
            else
            {
                buzzer_control.is_running = 0; // 完成蜂鸣器操作
            }
        }
    }
	else//目前是开，判断是否关闭
	{
		if(uwTick - buzzer_control.last_tick >= buzzer_control.on_time)
		{
			buzzer_off(); // 关闭蜂鸣器
			buzzer_control.state = 0; // 切换到关闭状态
			buzzer_control.last_tick = uwTick; // 更新最后操作时间
			buzzer_control.count++; // 增加计数
		}
	}

    
}